import logging

import pytest

from resource.pom.gallery import Gallery
from utils.manager import MatchRules


@pytest.fixture(scope='function', autouse=True)
def func_setup_teardown(device):
    logging.info('------用例前置：预置图片资源------')
    app = Gallery
    device.mediatool_delete_all()
    device.hdc_file_send(app.photo1, app.photo_dir)
    device.mediatool_send(app.photo_dir)
    yield
    logging.info('------用例后置：删除预置资源------')
    device.mediatool_delete_all()


class Test:
    app = Gallery

    @pytest.mark.parametrize('setup_teardown', [app.bundle_name], indirect=True)
    def test(self, setup_teardown, device):
        logging.info('步骤1.进入图片，点击选择一张图片')
        device.start_ability(self.app.bundle_name, self.app.ability_name)
        device.refresh_layout()
        device.click_element(device.get_element_by_key('TabPhotos'))
        device.refresh_layout()
        pic = device.get_element_by_key('ImageGridFocus_file', rule=MatchRules.Contain)
        device.click_element(device.get_element_by_key('Gesture_1'))

        logging.info('预期结果1.可以正常进入到图片')
        device.refresh_layout()
        device.assert_key_exist('PhotoBrowserBg')
        device.assert_key_exist('ActionBarButtonBack')
        device.assert_key_exist('PhotoBrowserDateTitle')
        device.assert_key_exist('DetailMenuPanel')
        device.assert_key_exist('ActionBarButtonInfo')
        device.assert_key_exist('ToolBarButtonFavor')
        device.assert_key_exist('ToolBarButtonEdit')
        device.assert_key_exist('ToolBarButtonDelete')
        device.assert_key_exist('ToolBarButtonMore')

        logging.info('步骤2.点击删除按钮，选择删除')
        device.click_element(device.get_element_by_key('ToolBarButtonDelete'))
        logging.info('预期结果2.显示“是否删除此图片”的提示，点击删除成功')
        device.refresh_layout()
        device.assert_text_exist('是否删除此图片', rule=MatchRules.Contain)
        device.assert_key_exist('DeleteDialogCancelButton')
        device.assert_key_exist('DeleteDialogConfirmButton')
        device.click_element(device.get_element_by_key('DeleteDialogConfirmButton'))

        logging.info('步骤3.查看图片结果')
        device.refresh_layout()
        logging.info('预期结果3.图库中此图片已不存在')
        # EmptyPhotoOrAlbumIco表示空白控件
        if device.get_element_by_key('EmptyPhotoOrAlbumIco'):
            return
        exist_pics = device.get_elements_by_key('ImageGridFocus_file', rule=MatchRules.Contain)
        if not exist_pics:
            return
        for p in exist_pics:
            if p.get('key') == pic.get('key'):
                raise AssertionError('图片删除失败')
